<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="500px" :title="`新订商品`">
    <p></p>
    <el-form ref="ruleFormRef" label-width="150px" label-suffix=" :" :rules="rules" :model="orderInfo">
      <el-form-item label="客户id" prop="customerName" style="display: flex; align-items: center">
        <el-input v-model="orderInfo!.customerName" placeholder="请输入客户名称" clearable style="flex: 1"></el-input>
        <el-button type="primary" @click="openCustomDialog">选择客户</el-button>
      </el-form-item>
      <el-form-item label="订单商品" prop="orderItems[0].goodsName" style="display: flex; align-items: center">
        <el-input
          v-model="orderInfo!.orderItems[0]!.goodsName"
          placeholder="请输入订单商品信息"
          clearable
          style="flex: 1"
        ></el-input>
        <el-button type="primary" @click="openGoodsDialog">选择商品</el-button>
      </el-form-item>
      <el-form-item label="商品数量" prop="orderItems[0].count">
        <el-input v-model="orderInfo!.orderItems[0]!.count" placeholder="请输入订单商品信息" clearable></el-input>
      </el-form-item>
      <el-form-item label="订单备注" prop="orderRemark">
        <el-input v-model="orderInfo!.orderRemark" placeholder="请输入订单备注信息" clearable></el-input>
      </el-form-item>
      <el-form-item label="收货地址（省）" prop="receiverAddress.province">
        <el-select v-model="orderInfo!.receiverAddress!.province" placeholder="请选择省份" @change="onProvinceChange">
          <el-option v-for="province in provinceList" :key="province" :label="province" :value="province"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="收货地址（市）" prop="receiverAddress.city">
        <el-select v-model="orderInfo!.receiverAddress!.city" placeholder="请选择城市" @change="onCityChange">
          <el-option v-for="city in cityList" :key="city" :label="city" :value="city"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="收货地址（区）" prop="receiverAddress.zone">
        <el-select v-model="orderInfo!.receiverAddress!.zone" placeholder="请选择区县">
          <el-option v-for="district in districtList" :key="district" :label="district" :value="district"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址" prop="receiverAddress.detail">
        <el-input v-model="orderInfo!.receiverAddress!.detail" placeholder="请输入客户详细地址" clearable></el-input>
      </el-form-item>
      <el-form-item label="收货人姓名" prop="receiverName">
        <el-input v-model="orderInfo!.receiverName" placeholder="请输入收货人姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="收货人电话" prop="receiverPhone">
        <el-input v-model="orderInfo!.receiverPhone" placeholder="请输入收货人电话" clearable></el-input>
      </el-form-item>
      <el-form-item label="是否需要发票" prop="optInvoice">
        <el-select v-model="orderInfo!.optInvoice" placeholder="请选择是否需要发票" clearable>
          <el-option label="是" :value="1"></el-option>
          <el-option label="否" :value="0"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
  <CustomDialog ref="customRef" @get-custom="getCustom" />
  <GoodsDialog ref="goodsRef" @get-goods="getGoods" />
</template>

<script setup lang="tsx" name="UserDrawer">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { addOrder } from "@/api/modules/custom";
import { useUserStore } from "@/stores/modules/user";
import CustomDialog from "./CustomDialog.vue";
import GoodsDialog from "./GoodsDialog.vue";
import { Custom, Good } from "@/api/interface";
import axios from "axios";
//import { provinceAndCityData, regionData, provinceAndCityDataPlus, regionDataPlus, CodeToText, TextToCode } from 'element-china-area-data'

const rules = reactive({
  customerId: [{ required: true, message: "请填写客户Id" }],
  customerName: [{ required: true, message: "请填写客户名称" }],
  "orderItems[0].goodsId": [{ required: true, message: "请填写商品Id" }],
  "orderItems[0].goodsName": [{ required: true, message: "请填写商品名称" }],
  "orderItems[0].count": [{ required: true, message: "请填写商品数量" }],
  orderRemark: [{ required: true, message: "请填写订单备注" }],
  "receiverAddress.province": [{ required: true, message: "请填写省份" }],
  "receiverAddress.city": [{ required: true, message: "请填写城市" }],
  "receiverAddress.zone": [{ required: true, message: "请填写地区" }],
  "receiverAddress.detail": [{ required: true, message: "请填写详细地址" }],
  receiverName: [{ required: true, message: "请填写S收货人姓名" }],
  receiverPhone: [
    { required: true, message: "请填写客户电话" },
    { pattern: /^1[3-9]\d{9}$/, message: "电话号格式不正确" }
  ],
  optInvoice: [{ required: true, message: "请填写是否需要发票" }]
});

//
// interface DrawerProps {
//   title: string;
//   isView: boolean;
//   row: Partial<any>;
//   api?: (params: any) => Promise<any>;
//   getTableList?: () => void;
// }

interface DrawerProps {
  title?: string;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerProps = ref<DrawerProps>({
  title: "新增客户"
});
const drawerVisible = ref(false);

const orderInfo = ref<Partial<any>>({
  orderType: 1,
  customerId: -1,
  customerName: "",
  orderItems: [
    {
      goodsId: -1,
      goodsName: "",
      goodsPrice: 0,
      count: undefined,
      measureUnit: ""
    }
  ],
  orderStatus: 0,
  orderRemark: "",
  receiverAddress: {
    province: "",
    city: "",
    zone: "",
    detail: ""
  },
  receiverName: "",
  receiverPhone: "",
  optInvoice: undefined,
  expDeliveryTime: new Date(),
  createTime: new Date(),
  creatorId: 0,
  updateTime: new Date()
});

const userStore = useUserStore();
// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  orderInfo.value.creatorId = userStore.userInfo.userId;
  orderInfo.value.createTime = new Date();
  orderInfo.value.updateTime = new Date();
  console.log(orderInfo.value);
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await addOrder(orderInfo.value);
      ElMessage.success({ message: `订单添加成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

const customRef = ref<InstanceType<typeof CustomDialog> | null>(null);
const openCustomDialog = () => {
  customRef.value?.open();
};

//获取子组件传来的分站信息
const getCustom = (row: Custom.ResCustomList) => {
  orderInfo.value!.customerId = row.customerId;
  orderInfo.value!.customerName = row.customerName;
};

const goodsRef = ref<InstanceType<typeof GoodsDialog> | null>(null);
const openGoodsDialog = () => {
  goodsRef.value?.open();
};

//获取子组件传来的分站信息
const getGoods = (row: Good.GoodsEntity) => {
  orderInfo!.value!.orderItems[0].goodsId = row.goodsId;
  orderInfo!.value!.orderItems[0].goodsName = row.goodsName;
  orderInfo!.value!.orderItems[0].measureUnit = row.measureUnit;
  orderInfo!.value!.orderItems[0].goodsPrice = row.goodsPrice;
};

const provinceList = ref([]);
const cityList = ref([]);
const districtList = ref([]);

const fetchProvinces = async () => {
  try {
    const response = await axios.get(
      "https://restapi.amap.com/v3/config/district?keywords=中国&subdistrict=1&key=7d36a7cce58b0b66bb018cc58cf3498f"
    );
    const provinces = response.data?.districts[0]?.districts || [];
    provinceList.value = provinces.map((province: any) => province.name);
  } catch (error) {
    console.error(error);
  }
};

const fetchCities = async (province: string) => {
  try {
    const response = await axios.get(
      `https://restapi.amap.com/v3/config/district?keywords=${province}&subdistrict=1&key=7d36a7cce58b0b66bb018cc58cf3498f`
    );
    const cities = response.data?.districts[0]?.districts || [];
    cityList.value = cities.map((city: any) => city.name);
  } catch (error) {
    console.error(error);
  }
};

const fetchDistricts = async (city: string) => {
  try {
    const response = await axios.get(
      `https://restapi.amap.com/v3/config/district?keywords=${city}&subdistrict=1&key=7d36a7cce58b0b66bb018cc58cf3498f`
    );
    const districts = response.data?.districts[0]?.districts || [];
    districtList.value = districts.map((district: any) => district.name);
  } catch (error) {
    console.error(error);
  }
};

const onProvinceChange = (province: string) => {
  orderInfo!.value.receiverAddress!.city = "";
  orderInfo!.value.receiverAddress!.zone = "";
  fetchCities(province);
};

const onCityChange = (city: string) => {
  orderInfo!.value.receiverAddress!.zone = "";
  fetchDistricts(city);
};

onMounted(() => {
  fetchProvinces();
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

defineExpose({
  acceptParams
});
</script>
